package pers.lan.linkedlist;

/**
 * @author lan
 * @date 2020/9/25
 */
public class HL_20200925 {

    public static void main(String[] args) {
        ListNode l1 = ListNode.build(new int[]{2, 0, 0, 1});
        ListNode l2 = ListNode.build(new int[]{9, 9, 9});
        ListNode res = addTwoNumbers(l1, l2);
        System.out.println(res);
    }

    private static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1, p2 = l2;
        ListNode head = new ListNode(0);
        ListNode p = head;

        int cb = 0;
        while (p1 != null && p2 != null) {
            cb = buildNextNode(p, p1.val + p2.val + cb);
            p = p.next;
            p1 = p1.next;
            p2 = p2.next;
        }
        while (p1 != null) {
            cb = buildNextNode(p, p1.val + cb);
            p = p.next;
            p1 = p1.next;
        }
        while (p2 != null) {
            cb = buildNextNode(p, p2.val + cb);
            p = p.next;
            p2 = p2.next;
        }
        if (cb > 0) {
            buildNextNode(p, cb);
        }

        return head.next;
    }

    private static int buildNextNode(ListNode node, int val) {
        if (val > 9) {
            node.next = new ListNode(val - 10);
            return 1;
        }
        node.next = new ListNode(val);
        return 0;
    }
}
